# 1 楼答案 您可以使用: Collections.replaceAll(list, "two", "one"); 从the documentation: Replaces all occurrences of one specified value in a list with another. More formally, replaces with newVal each element e in list such that (oldVal==null ? e==null : oldVal.equals(e)). (This method has no effect on the size of the list.) 该方法还返回一个boolean,以指示是否实际进行了任何替换 ^{}有更多的static实用方法,您可以在List上使用(例如sort、binarySearch、shuffle等) 片段 下面展示了Collections.replaceAll的工作原理;它还显示,您还可以替换到null或从null替换: List<String> list = Arrays.asList( "one", "two", "three", null, "two", null, "five" ); System.out.println(list); // [one, two, three, null, two, null, five] Collections.replaceAll(list, "two", "one"); System.out.println(list); // [one, one, three, null, one, null, five] Collections.replaceAll(list, "five", null); System.out.println(list); // [one, one, three, null, one, null, null] Collections.replaceAll(list, null, "none"); System.out.println(list); // [one, one, three, none, one, none, none]
# 1 楼答案
您可以使用:
从the documentation:
该方法还返回一个
boolean
,以指示是否实际进行了任何替换^{} 有更多的
static
实用方法,您可以在List
上使用(例如sort
、binarySearch
、shuffle
等)片段
下面展示了
Collections.replaceAll
的工作原理;它还显示,您还可以替换到null
或从null
替换: